//
//  SeekViewController.m
//  SugarPile
//
//  Created by Charlie. on 16/1/27.
//  Copyright © 2016年 www.lanou39.蓝鸥科技. All rights reserved.
//

#import "SeekViewController.h"
#import "LCPrefixHeader.pch"
#import "HotModel.h"
#import "HotDetailsViewController.h"
@interface SeekViewController ()<UISearchResultsUpdating, UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, retain) UISearchController *search;/**< 搜索控制视图 */
@property (nonatomic, copy) NSString *strHight;/**< 高亮用字符串 保存搜索信息 */
@property (nonatomic, retain) NSMutableArray *companyArr;/**< 搜索到公司数组 */
@property (nonatomic, assign) BOOL is;
@property (nonatomic, retain) UITableView *tableView;

@end

@implementation SeekViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
     [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)forBarMetrics:UIBarMetricsDefault];//导航条返回键带的首页 让他消失
   

    _is = YES;
    // 创建tableView
    [self createTableView];
    // 初始化搜索视图
    self.search = [[UISearchController alloc] initWithSearchResultsController:nil];
    // 签订协议
    _search.searchResultsUpdater = self;
    
    // 屏幕不变灰 yes时tableview 不能下拉
    _search.dimsBackgroundDuringPresentation = NO;
    
    // 设置点击搜索框时隐藏导航栏
    _search.hidesNavigationBarDuringPresentation = NO;
    
    // 位置自适应
    [_search.searchBar sizeToFit];
    
    // 把搜索视图加载导航栏上
    self.navigationItem.titleView = _search.searchBar;

    
    
    // 创建右边搜索
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:(UIBarButtonItemStylePlain) target:self action:@selector(searchNews)];
    self.navigationItem.rightBarButtonItem = rightItem;
}
- (void)searchNews
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:(UITableViewStylePlain)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [_tableView release];
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
}
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    
    
    // 将搜索内容转化为字符串
    // 等同于 获取搜索的信息
    self.strHight = [self.search.searchBar text];
    
    if ([_strHight containsString:@" "]) {
        
        

        NSLog(@"无结果");
        // 字符串有空格的时候 搜索会崩溃
        // 判断如果有空格不执行
        // 没有执行以下程序
        
    } else {
       
        // 拼接
        NSString *urlStr = [_strHight stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:_strHight]];
        // 中文转码
        NSString *url =[@"http://203.80.144.212/napi/blog/list/by_search/?include_fields=sender%2Calbum%2Cicon_url%2Creply_count%2Clike_count&platform_version=4.4.4&device_platform=HM%2B2A&__dtac=%257B%2522_r%2522%253A%2520%2522350505%2522%257D&screen_width=720&screen_height=1280&__domain=www.duitang.com&app_version=68&kw=叶子&start=0&platform_name=Android&locale=zh&app_code=nayutas" stringByReplacingOccurrencesOfString:@"kw=叶子" withString:[NSString stringWithFormat:@"kw=%@", urlStr]];
        NSLog(@"%@", url);
        
      [LCAFNetWorking GETWithURL:url completion:^(id result) {
            NSArray *arr = result[@"data"][@"object_list"];
            self.companyArr = [HotModel modelHanderWithArray:arr];
          
          if (_companyArr.count == 0) {
              UIAlertController *al = [UIAlertController alertControllerWithTitle:@"提示" message:@"已经收藏" preferredStyle:UIAlertControllerStyleAlert];
              //显示
              [self presentViewController:al animated:YES completion:^{
                  // 一秒后执行diss方法
                  [self performSelector:@selector(diss:) withObject:self afterDelay:1];
                  
              }];

              NSLog(@"无结果");
          }
          
            [_tableView reloadData];

        }];
        
    }
    
    
}
- (void)diss:(id)a
{
    [self dismissViewControllerAnimated:YES completion:^{
    }];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _companyArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    HotModel *m = _companyArr[indexPath.row];
    
    ///高亮设置
    NSMutableAttributedString *attrituteString = [[NSMutableAttributedString alloc] initWithString:m.msg];
    NSRange range = [m.msg rangeOfString:_strHight];
    [attrituteString setAttributes:@{NSForegroundColorAttributeName : [UIColor redColor],   NSFontAttributeName : [UIFont systemFontOfSize:18]} range:range];
    
    cell.textLabel.attributedText = attrituteString;
    
    return cell;
}
// 点击跳转方法
- (void)tableView:(UITableView *)tableView didHighlightRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
  
        
        HotDetailsViewController *hotVC = [[[HotDetailsViewController alloc] init] autorelease];
        hotVC.hidesBottomBarWhenPushed = YES;
        HotModel *m = _companyArr[indexPath.row];
        hotVC.detailsId = m.ID;
        [self.navigationController pushViewController:hotVC animated:YES];
  
    
    
}

//-(void)viewWillAppear:(BOOL)animated
//{
//    [super viewWillAppear:animated];
//    [self.companyArr removeAllObjects];
//    [self.tableView reloadData];
//}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

    if (_is) {
        
        _is = NO;
        [self searchNews];

    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
